//
//  PersonalViewController.m
//  项目三
//
//  Created by rimi1 on 2016/12/9.
//  Copyright © 2016年 Wangxingqian. All rights reserved.
//

#import "PersonalViewController.h"
#import "SignInViewController.h"// 登录界面
#import "PersonalInfoViewController.h"// 个人信息
#import "PersonalFCViewController.h"// 关注和粉丝
#import "CommentViewController.h"// 个人作品
#import "DetailViewController.h"// 系统菜谱详情

#import "PersonalHeadView.h"// 头部视图
#import "MenuListTableViewCell.h"// cell

#import "AVRequest+Relation.h"

@interface PersonalViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) PersonalHeadView *headView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <AVObject *> *menuArr;
@property (nonatomic, strong) NSMutableArray <AVObject *> *collectArr;

@end

@implementation PersonalViewController

- (void)viewWillAppear:(BOOL)animated {
    // 根据是否登录状态布局
    [self.headView signInWithIs:[MyUser sharedUser].isSignIn];
    [self initHead];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    [self initializeAppearance];
}

#pragma mark - initialize

- (void)initializeDataSource {
    self.menuArr = [NSMutableArray array];
    self.collectArr = [NSMutableArray array];
    // 登录状态时
    if ([MyUser sharedUser].isSignIn) {
        [self urlDynamicRequest];
        [self urlCollectRequest];
        [self urlUserRequest];
    }
}

- (void)initializeAppearance {
    self.navigationBar.title.text = @"个人中心";
    self.tableView.tableHeaderView = self.headView;
    [self.headView.myMenu setTitle:@"个人作品" forState:UIControlStateNormal];
    [self.view addSubview:self.tableView];
}

- (void)initHead {
    [self.headView fcAssignmentWithFansCount:[MyUser sharedUser].fansCount concernCount:[MyUser sharedUser].concernCount];
    self.headView.name.text = [MyUser sharedUser].name;
    NSURL *url = [NSURL URLWithString:[MyUser sharedUser].headImage];
    [self.headView.headImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"个人"] options:SDWebImageProgressiveDownload];
}

#pragma mark - URLRquest
// 个人作品
- (void)urlDynamicRequest {
    AVObject *obj = [AVObject objectWithClassName:@"MyUser" objectId:[MyUser sharedUser].userId];
    [AVRequest avDynamicWithObj:obj query:^(NSArray *objects, NSError *error) {
        if (error) {
            return;
        }
        self.menuArr = [NSMutableArray array];
        for (NSInteger i = objects.count - 1; i >= 0; i--) {
            [self.menuArr addObject:objects[i]];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
    }];
}
// 收藏
- (void)urlCollectRequest {
    AVObject *obj = [AVObject objectWithClassName:@"MyUser" objectId:[MyUser sharedUser].userId];
    [AVRequest avCollcetWithObj:obj query:^(NSArray *objects, NSError *error) {
        if (error) {
            return;
        }
        self.collectArr = [NSMutableArray array];
        for (NSInteger i = objects.count - 1; i >= 0; i--) {
            [self.collectArr addObject:objects[i]];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
    }];
}
// 刷新个人信息
- (void)urlUserRequest {
    AVQuery *query = [AVQuery queryWithClassName:@"MyUser"];
    [query whereKey:@"objectId" equalTo:[MyUser sharedUser].userId];
    [AVRequest avQueryWithQuery:query queryArr:^(NSArray *objects, NSError *error) {
        if (error) {
            return;
        }
        [self.tableView.mj_header endRefreshing];
        [MyUser initUserWithObj:objects.firstObject];
        [self initHead];
    }];
}

- (void)downPullRefresh {
    if ([MyUser sharedUser].isSignIn) {
        [self urlDynamicRequest];
        [self urlCollectRequest];
        [self urlUserRequest];
    }else {
        [self.tableView.mj_header endRefreshing];
    }
}

#pragma mark - Custom Method

- (void)signOut {
    self.menuArr = [NSMutableArray array];
    self.collectArr = [NSMutableArray array];
    [self initHead];
    [self.tableView reloadData];
}
// 点击个人作品时，跳转
- (void)tapPersonalCellWithObj:(AVObject *)obj {
    CommentViewController *comment = [[CommentViewController alloc] init];
    comment.obj = obj;
    [self.navigationController pushViewController:comment animated:YES];
}

#pragma mark - respondsTo..

- (void)respondsToHead {
    PersonalInfoViewController *info = [[PersonalInfoViewController alloc] init];
    
    __weak PersonalViewController *personal = self;
    info.signOutBlock = ^() {
        [personal signOut];
    };
    [self.navigationController pushViewController:info animated:YES];
}
// 100：粉丝  101：关注  102：菜谱  103：收藏
- (void)respondsToButton:(UIButton *)sender {
    NSInteger tag = sender.tag;
    if (tag == 100 || tag == 101) {
        BOOL isFC;
        if (tag == 100) {
            isFC = NO;
        }else {
            isFC = YES;
        }
        
        PersonalFCViewController *fc = [[PersonalFCViewController alloc] init];
        AVObject *obj = [AVObject objectWithClassName:@"MyUser" objectId:[MyUser sharedUser].userId];
        fc.obj = obj;
        fc.isSelf = YES;
        fc.isFC = isFC;
        [self.navigationController pushViewController:fc animated:YES];
        
    }else if (tag == 102) {
        sender.selected = YES;
        self.headView.myCollect.selected = NO;
        [self.tableView reloadData];
    }else if (tag == 103) {
        sender.selected = YES;
        self.headView.myMenu.selected = NO;
        [self.tableView reloadData];
    }
}
// 登录
- (void)respondsToSignIn:(UIButton *)sender {
    SignInViewController *signIn = [[SignInViewController alloc] init];
    
    __weak PersonalViewController *personal = self;
    signIn.signInSucceed = ^() {
        [personal urlDynamicRequest];
        [personal urlCollectRequest];
    };
    [self.navigationController pushViewController:signIn animated:YES];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.headView.myMenu.selected) {
        return self.menuArr.count;
    }else {
        return self.collectArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reusing = @"PersonalTableViewCell";
    MenuListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reusing];
    if (!cell) {
        cell = [[MenuListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusing];
    }
    AVObject *obj;
    if (self.headView.myMenu.selected) {
        obj = self.menuArr[indexPath.row];
    }else {
        obj = self.collectArr[indexPath.row];
    }
    
    NSURL *url = [NSURL URLWithString:obj[@"img"]];
    [cell.imageViewList sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"默认加载图"] options:SDWebImageProgressiveDownload];
    cell.name.text = obj[@"name"];
    cell.food.text = obj[@"food"];
    
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

#pragma mark - UITableViewDelgeatae

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    AVObject *obj;
    if (self.headView.myMenu.selected) {
        obj = self.menuArr[indexPath.row];
        [self tapPersonalCellWithObj:obj];
    }else {
        obj = self.collectArr[indexPath.row];
        // 存在为个人作品，不存在则是系统菜谱
        if (obj[@"dynamic"]) {
            [self tapPersonalCellWithObj:obj[@"dynamic"]];
        }else {
            DetailViewController *detai = [[DetailViewController alloc] init];
            detai.menuId = obj[@"id"];
            [self.navigationController pushViewController:detai animated:YES];
            
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return WXQAdaptionHeight(115);
}

#pragma mark - get

- (PersonalHeadView *)headView {
    
    if (!_headView) {
        
        _headView = [[PersonalHeadView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, WXQAdaptionHeight(210))];
        
        __weak PersonalViewController *personal = self;
        _headView.tapHead = ^() {
            [personal respondsToHead];
        };
        _headView.tapButton = ^(UIButton *sender) {
            [personal respondsToButton:sender];
        };
        _headView.tapSignIn = ^(UIButton *sender) {
            [personal respondsToSignIn:sender];
        };
        
    }
    return _headView;
}

- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kWIDTH, kHEIGHT - 64) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downPullRefresh)];
        
    }
    return _tableView;
}

@end











